package com.gamotech.schoollifedemo.utils

import android.os.Build
import android.util.Base64
import androidx.annotation.RequiresApi
import java.security.MessageDigest
import java.util.*

class EncryptUtils {
    fun init() {}

    fun convert2SHA256(value: String): String {
        val digest = MessageDigest.getInstance("SHA-256")
        val convertByteArray: ByteArray = digest.digest(value.toByteArray())
        return toHex(convertByteArray)
    }

    fun convert2MD5(value: String): String {
        val digest = MessageDigest.getInstance("MD5")
        val convertByteArray: ByteArray = digest.digest(value.toByteArray())
        return toHex(convertByteArray)
    }


    fun encodeBase64(value: String?): String? {
        if (value == null) {
            return null
        }
        return Base64.encodeToString(value.toByteArray(), Base64.URL_SAFE)
    }

    fun decodeBase64(value: String?): String? {
        if (value == null) {
            return null
        }
        val convertByteArray = Base64.decode(value, Base64.URL_SAFE)
        return String(convertByteArray)
    }

    private fun toHex(byteArray: ByteArray): String {
        val result = with(StringBuilder()) {
            byteArray.forEach {
                val hex = it.toInt() and (0xFF)
                val hexStr = Integer.toHexString(hex)
                if (hexStr.length == 1) {
                    this.append("0").append(hexStr)
                } else {
                    this.append(hexStr)
                }
            }
            this.toString()
        }
        //转成16进制后是32字节
        return result
    }

    fun dispose() {}
}